const state = {
  isAuthenticated: false,
  user: null,
  loading: false,
  error: null
}

const mutations = {
  SET_AUTH_STATE(state, { isAuthenticated, user }) {
    state.isAuthenticated = isAuthenticated
    state.user = user
    state.error = null
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  }
}

const actions = {
  async login({ commit }, { username, password }) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      // 这里应该调用后端API进行验证
      // 目前使用模拟数据
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          if (username && password) {
            resolve()
          } else {
            reject(new Error('用户名和密码不能为空'))
          }
        }, 1000)
      })

      commit('SET_AUTH_STATE', {
        isAuthenticated: true,
        user: { username }
      })
      
      // 保存到localStorage以保持登录状态
      localStorage.setItem('user', JSON.stringify({ username }))
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  async register({ commit }, { username, password }) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      // 这里应该调用后端API进行注册
      // 目前使用模拟数据
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          if (username && password) {
            if (username.length < 3) {
              reject(new Error('用户名至少需要3个字符'))
              return
            }
            if (password.length < 6) {
              reject(new Error('密码至少需要6个字符'))
              return
            }
            resolve()
          } else {
            reject(new Error('用户名和密码不能为空'))
          }
        }, 1000)
      })
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  logout({ commit }) {
    localStorage.removeItem('user')
    commit('SET_AUTH_STATE', {
      isAuthenticated: false,
      user: null
    })
  },

  // 检查本地存储中的登录状态
  checkAuth({ commit }) {
    const userData = localStorage.getItem('user')
    if (userData) {
      try {
        const user = JSON.parse(userData)
        commit('SET_AUTH_STATE', {
          isAuthenticated: true,
          user
        })
      } catch (error) {
        console.error('Failed to parse user data:', error)
        localStorage.removeItem('user')
      }
    }
  }
}

const getters = {
  isAuthenticated: state => state.isAuthenticated,
  currentUser: state => state.user,
  isLoading: state => state.loading,
  error: state => state.error
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 